#! /usr/bin/python3

import argparse
import os, sys, shutil


from SalomeOnDemandTK.extension_utilities import logger, \
    INSTALLFILE_EXT, BFILE_EXT, DFILE_EXT, ENVPYFILE_SUF, ARCFILE_EXT

# get salome_appli_dir
try:
    salome_appli_dir = os.environ["SALOME_APPLICATION_DIR"]
except:
    salome_bootstrap_dir = os.path.dirname(os.path.realpath(__file__))
    salome_appli_dir = os.path.dirname(salome_bootstrap_dir)

ext_pkg_dir = os.path.join(salome_appli_dir,"ext_pkg")

def install(extname):
    """ Install extension module in salome_appli_dir
    extname: extension module name
    """
    ext_pkg_name = extname + '.' + ARCFILE_EXT
    ext_pkg_dir_name = os.path.join(ext_pkg_dir,ext_pkg_name)
    if not os.path.isfile(ext_pkg_dir_name):
        logger.error( "Extension package {} does not exist.\nPlease be sure that you have this package in {}"
        .format(ext_pkg_name, ext_pkg_dir_name) )
        return 1
    # Remove old extension
    remove(extname)

    # Unpack the new extension
    logger.info("Install %s"%extname)
    os.environ["SALOME_APPLICATION_DIR"] = salome_appli_dir
    import SalomeOnDemandTK.extension_unpacker as extension_unpacker
    extension_unpacker.install_salomex(ext_pkg_dir_name)
    #extension_unpacker.unpack_salomex(salome_appli_dir, ext_pkg_dir_name)

def remove(extname):
    """ Remove extension module from salome_appli_dir
    extname: extension module name
    """
    logger.info("Remove %s"%extname)
    import SalomeOnDemandTK.extension_remover as extension_remover
    extension_remover.remove_salomex(salome_appli_dir, extname)

def create(extname, packaging_script_dir, src_binaries_dir):
    """ Packaging salomex
    extname: module name
    packaging_script_dir: path to directory of packaging scripts (salomexd, salomexb, _env.py)
    src_binaries_dir: salome module installation directory
    """
    logger.info('Create package %s, with packaging script in %s directory, and the binaries in %s directory'%(extname, packaging_script_dir, src_binaries_dir))
    import SalomeOnDemandTK.extension_builder as extension_builder

    ext_config_files = []
    for file_ext in ['.' + BFILE_EXT, '.' + DFILE_EXT, ENVPYFILE_SUF]:
        ext_config_files.append(os.path.join(packaging_script_dir, extname + file_ext))
    ext_post_install_script = os.path.join(packaging_script_dir, extname + '.' + INSTALLFILE_EXT)
    if not os.path.isfile(ext_post_install_script):
        print(ext_post_install_script)
        ext_post_install_script = None
    extension_builder.create_salomex( *ext_config_files, src_binaries_dir, post_install_script = ext_post_install_script, auto = True )
    ext_pkg_name = extname + '.' + ARCFILE_EXT
    if not os.path.isdir(ext_pkg_dir):
        os.mkdir(ext_pkg_dir)
    shutil.move( ext_pkg_name, os.path.join(ext_pkg_dir,ext_pkg_name) )
    

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('mode', default=argparse.SUPPRESS, help='We have 3 function in this executable: install, remove, create')
    parser.add_argument('-p', '--package',default = argparse.SUPPRESS, help = 'extension package name',
                        required='install' in sys.argv or 'remove'in sys.argv or 'create' in sys.argv)
    parser.add_argument('-s', '--scriptdir', default = argparse.SUPPRESS, help = 'extension packaging script dir', required = 'create'in sys.argv)
    parser.add_argument('-b', '--binariesdir', default = argparse.SUPPRESS, help = 'extension binaries dir', required = 'create'in sys.argv )

    args = parser.parse_args()

    if args.mode == 'install' or args.mode == 'remove':
        res = globals()[args.mode](args.package)
    elif args.mode == 'create':
        res = globals()[args.mode](args.package, args.scriptdir, args.binariesdir)
    else:
        logger.error("%s mode is not found"%args.mode)
        parser.print_help()
